/*API = {
	searchUsersByUsername: "http://127.0.0.1:6011/elcs/api/v1/user/ext/searchByUsername"
}*/

//定义全局变量：
var chooseUserData = {
	currentUsers: {},
	checkedUsers: {},
	msgid:null
};

/*************************点击用户Panel相关事件********************/

//全选
$(document).on('click', '#encryptedMsgModal .user-wrapper table thead input', function() {
	var userArr = [];
	for(var key in chooseUserData.currentUsers) {
		if(chooseUserData.currentUsers.hasOwnProperty(key) === true) {
			userArr.push(chooseUserData.currentUsers[key]);
		}
	}
	if($(this).prop("checked")) {
		EMcheckUsersOperation.addUsers(userArr);
	} else {
		EMcheckUsersOperation.removeUsers(userArr);
	}

});

$(document).on('click', '#encryptedMsgModal .em-user-wrapper table tbody input', function() {
	if($(this).prop("checked")) {
		var currentCheckedUser = chooseUserData.currentUsers[$(this).data('userid')];
		console.log(chooseUserData.currentUsers.length)
		EMcheckUsersOperation.addUsers([currentCheckedUser]);
	} else {
		var currentCheckedUser = chooseUserData.currentUsers[$(this).data('userid')];
		EMcheckUsersOperation.removeUsers([currentCheckedUser]);
	}

});

/*************************取消选择用户事件********************/
$(document).on('click', '#encryptedMsgModal .em-selected-user table tbody i', function() {
	var user = chooseUserData.checkedUsers[$(this).data('userid')];
	EMcheckUsersOperation.removeUsers([user]);

});

/*********************************选择处理***************************/

EMcheckUsersOperation = {
	addUsers: function(users) {
		for(var i = 0; i < users.length; i++) {
			//处理右则显示
			var currentObjLen = $("#encryptedMsgModal .em-right-panel [data-userid=" + users[i].account + "]").length;
			//如果还没有,添加
			if(currentObjLen == 0) {

				var account = users[i].account,
					avatar = getAvatar(yunXin.cache.getUserById(account) ? yunXin.cache.getUserById(account).avatar : ""),
					nick = getNick(account)

				var $trObj = $(`<tr>
									<td><img src='`+ avatar +`' class='zdy-userImg'/></td>
									<td>
										<p class='em-userName'>` + nick + `</p>
									</td>
									<td><i class='iconfont icon-cancel' data-userid='` + account + `'></i></td>
								</tr>`)
				$("#encryptedMsgModal .em-right-panel table tbody").append($trObj);
			}

			//处理数据
			chooseUserData.checkedUsers[users[i].account] = users[i];

			//处理中间
			$("#encryptedMsgModal .em-user-wrapper input[data-userid=" + users[i].account + "]").prop("checked", "checked");

			//计算当前选择的节点同父节点的数量
			var count = 0;
			for(var key in chooseUserData.checkedUsers) {
				//只遍历对象自身的属性，而不包含继承于原型链上的属性。  
				if(chooseUserData.checkedUsers.hasOwnProperty(key) === true) {
					if(chooseUserData.checkedUsers[key].node_uuid == users[i].node_uuid) {
						count++;
					}
				}
			}

		}
		//更新个数
		var totalCount = Object.getOwnPropertyNames(chooseUserData.checkedUsers).length;
		$("#encryptedMsgModal .em-right-panel .em-user-count span").text(totalCount);
	},
	removeUsers: function(users) {
		//处理数据
		for(var i = 0; i < users.length; i++) {

			//处理显示
			var currentObjLen = $("#encryptedMsgModal .em-right-panel [data-userid=" + users[i].account + "]").length;
			$("#encryptedMsgModal .em-right-panel tr i[data-userid=" + users[i].account + "]").closest("tr").remove();

			//处理数据
			delete chooseUserData.checkedUsers[users[i].account];

			//处理中间
			$("#encryptedMsgModal .em-user-wrapper input[data-userid=" + users[i].account + "]").prop("checked", "");

			//当前table也要取消打勾
			$('#encryptedMsgModal .em-user-wrapper table thead input').prop("checked", "");

		}

		//更新个数
		var totalCount = Object.getOwnPropertyNames(chooseUserData.checkedUsers).length;
		$("#encryptedMsgModal .em-right-panel .em-user-count span").text(totalCount);
	},
	getAllUsersByUUIds: function(uuids, callback) {
		var notFetchUuids = [];
		for(var i = 0; i < uuids.length; i++) {
			if(!chooseUserData.saveNodes[uuids[i]]) {
				notFetchUuids.push(uuids[i]);
			}
		}

		var data = {
			uuids: notFetchUuids
		};
		if(notFetchUuids.length == 0) {
			callback(uuids);
		} else {
			sendRequest(API.getAllUsersByUUIds, "post", data, function(result) {
				if(result.code == 0) {
					var users = result.data;

					for(var i = 0; i < notFetchUuids.length; i++) {
						//不管有没有获取用户数据,记录uuid,防止下次继续请求获取
						chooseUserData.saveNodes[notFetchUuids[i]] = {};
					}

					for(var i = 0; i < users.length; i++) {
						//缓存用户数据
						if(!chooseUserData.saveNodes[users[i].node_uuid]) {
							chooseUserData.saveNodes[users[i].node_uuid] = {};
						}
						chooseUserData.saveNodes[users[i].node_uuid][users[i].id] = users[i];
					}

					callback(uuids);
				}
			});
		}
	}
}

/***************************************智能搜索*********************************/
var setTimeoutId;
$("#encryptedMsgModal .em-left-panel .em-search input").keyup(function() {
	$("#encryptedMsgModal .em-search ul li").remove();
	$("#encryptedMsgModal .em-search .em-search-list-wrapper").hide();

	if($(this).val().length < 1) {
		return;
	}
	//延迟请求500ms
	clearTimeout(setTimeoutId);
	var url = API.searchUsersByUsername + '?keyword=' + $(this).val() + '&pageno=1&pagesize=10';
	setTimeoutId = setTimeout(function() {
		sendRequest(url, "get", undefined, function(result) {
			if(result.code == 0) {
				if(result.data.length == 0) {
					$("#encryptedMsgModal .em-search .em-search-list-wrapper").hide();
				} else {
					$("#encryptedMsgModal .em-search .em-search-list-wrapper").show();
				}
				for(var i = 0; i < result.data.length; i++) {
					var domString = '<li>\
							<a href="#" data-nodeuuid="' + result.data[i].node_uuid + '" data-userid="' + result.data[i].id + '">' + result.data[i].user_name + ' ' + result.data[i].title + ' ' + result.data[i].full_name + '</a>\
						</li>';
					$("#encryptedMsgModal .search ul").append(domString);
				}
			}
		});
	}, 500);

});

$(document).on("click", "#encryptedMsgModal .em-search ul a", function() {
	$("#encryptedMsgModal .em-search .em-search-list-wrapper").hide();
	var node_uuid = $(this).data('nodeuuid');
	var user_id = $(this).data('userid');
	var treeObj = $.fn.zTree.getZTreeObj("nodeTree");
	var node = treeObj.getNodeByParam("uuid", node_uuid);

	//展开对应节点
	var nodes = node.getPath();
	if(nodes.length > 2) {
		treeObj.expandNode(nodes[nodes.length - 2], true, false);
	}

	EMcheckUsersOperation.getAllUsersByUUIds([node_uuid], function() {

		//触发点击事件，显示对应节点数据
		$("#" + node.tId + "_a .name").click();
		EMcheckUsersOperation.addUsers([chooseUserData.saveNodes[node_uuid][user_id]]);

		//树形滚动到目标节点:
		$("#encryptedMsgModal .left-panel .tree-wrapper").mCustomScrollbar('scrollTo', "#" + node.tId + "_a .name");

	});
});

/*********************************暴露调用**************************/
function EMchooseUser(callback) {
	Modal.show("#encryptedMsgModal");
	$("#encryptedMsgModal .em-confirm").click(function() {
		//判断是否做了选择
		var chooseUserLen = Object.getOwnPropertyNames(chooseUserData.checkedUsers).length;
		if(chooseUserLen == 0) {
			return;
		}

		//整理成数组:
		var userArr = [];
		for(var key in chooseUserData.checkedUsers) {
			//只遍历对象自身的属性，而不包含继承于原型链上的属性。  
			if(chooseUserData.checkedUsers.hasOwnProperty(key) === true) {
				userArr.push(chooseUserData.checkedUsers[key]);
			}
		}

		//向回调函数传入选择的用户
		if(callback) {
			callback(userArr);
		}
		Modal.hide("#encryptedMsgModal");
	});

	$("#encryptedMsgModal .em-cancel").click(function() {
		Modal.hide("#encryptedMsgModal");
	});
}